import { requestApi } from "../../utils/util";
import { API_URLS } from '../../api/index.js';
;

const DEVICE_TREE_PAGE_SIZE = 99
const searchTreeMixin = {
  // import { mapGetters, mapActions } from 'vuex';
  // import { flatten } from '@/utils/util';
  data() {
    return {
      expandedKeys: [], // 展开的节点
      treeData: [],
      pageNoCode: 1,
      pageNoName: 1
    };
  },
  methods: {
    // isConcat: 是否在已有数据基础上拼接合并
    updateTreeData(data, isConcat = false) {
      this.treeData = isConcat ? this.treeData.concat(data) : data;
      this.treeData = [...this.treeData];
    },
    /**
     * 获取树节点数据，分地区数据和最底层的设备数据
     * @param parentId - 节点id，不传或为空表示请求根节点
     * @param hasChildren - 是否获取区域列表
     * @param isGetDeviceList - 是否获取设备列表，请求树结构中的地区数据和设备数据的接口不同
     * @param showLoading - 请求数据时是否显示加载loading
     * @param refreshNode - 刷新当前节点
     */
    getTreeData(params = {}) {
      const {
        isSearch = false,
        parentId = '',
        isGetDeviceList = false,
        hasChildren,
        showLoading = false,
        refreshNode,
        pageNo = 1,
        parentRealRegionCode
      } = params;
      // if(parentId) {
      //   // 更新该节点的设备数量显示
      //   this.updateDeviceCount(parentId,2,showLoading);
      // }
      console.log('getTreeData', params);
      let p = [];
      if (!parentId || hasChildren) {
        // 获取地区/分组列表（有子节点）
        let paramsTree = {
          type: this.treeType,
          isSearchClick: isSearch
        };
        if (parentId) paramsTree.parentRegionCode = parentId;
        p.push(this.getRegionList(parentRealRegionCode, paramsTree, showLoading || !parentId));
      }
      if (isGetDeviceList) {
        // 获取设备列表（无子节点）
        let params = {
          type: this.treeType,
          regionId: parentId,
          pageSize: DEVICE_TREE_PAGE_SIZE,
          pageNo: pageNo
        };
        p.push(this.getRegionDeviceList(params, showLoading || !parentId));
      }
      return Promise.all(p).then((res) => {
        let nodeList =
          res?.length === 2
            ? res[0].list.concat(res[1].list)
            : res?.length === 1
            ? res[0].list
            : [];
        // console.log('节点children：',nodeList);
        // 节点下设备列表分页信息
        let childrenPagination = {};
        let resInfo = res.find((item) => item.isDevice);
        // console.log('设备节点resInfo：',resInfo, res);
        if (resInfo) {
          const { pagination, error } = resInfo;
          childrenPagination = {
            ...(error ? {} : pagination),
            pageNo: pageNo
          };
        }

        if (!parentId) {
          // 根节点数据
          this.updateTreeData(nodeList, true);
        } else {
          // 添加子节点
          let updateParent = {};
          if (refreshNode) {
            this.getNodeDeviceNum(parentId, showLoading).then(({ deviceCount }) => {
              updateParent = { deviceCount: deviceCount };
              let { arr } = this.insertTreeChildren(
                this.treeData,
                parentId,
                nodeList,
                childrenPagination,
                updateParent
              );
              this.updateTreeData(arr);
            });
          } else {
            let { arr } = this.insertTreeChildren(
              this.treeData,
              parentId,
              nodeList,
              childrenPagination
            );
            this.updateTreeData(arr);
          }
        }
      });
    },

    // 获取节点区域节点列表
    getRegionList(parentRealRegionCode, params, showLoading) {
      return new Promise((resolve) => {
        const { regionId } = params;
        if (regionId && this.treeType === 2) {
          // 只有监控目录才需要查询区域层级，“我的设备”直接查询搜索结果
          requestApi({
            url: API_URLS.getRegions,
            method: 'post',
            data: { ...params },
            headers:{
              AccessToken: this.cardInfo.accessToken
            }
          }).then((res) => {
              if (res && res.reginWithGroupList) {
                let list = res.reginWithGroupList.map((item) => {
                  return {
                    ...item,
                    key: '' + item.regionCode,
                    isLeaf: false,
                    selectable: true,
                    // title: `${item.name}(${item.onlineDeviceCount||0}/${item.deviceCount||0})`,
                    title: item.name,
                    onlineDeviceCount: item.onlineDeviceCount || 0,
                    deviceCount: item.deviceCount || 0,
                    scopedSlots: {
                      title: 'title',
                      icon: 'titleIcon'
                    },
                    keyPath: '',
                    pathName: ''
                  };
                });
                // 获取各节点设备数量
                this.updateListDeviceNum(parentRealRegionCode, list, showLoading)
                  .then((r) => {
                    list = r;
                  })
                  .finally(() => {
                    resolve({ list });
                  });
              } else {
                res && res.msg && this.$message.error(res.msg);
                resolve({ list: [] });
              }
            })
            .catch(() => {
              resolve({ list: [] });
            });
        } else if (!regionId) {
          // 搜索首层树
          console.log('searchType:::', this.searchType);
          if (this.searchType === '1') {
            this.searchByRegion(params).then((res) => {
              resolve(res);
            });
          } else if (this.searchType === '2') {
            this.searchByDeviceName(params).then((res) => {
              resolve(res);
            });
          } else if (this.searchType === '3') {
            this.searchByDeviceCode(params).then((res) => {
              resolve(res);
            });
          } else {
            resolve({ list: [] });
          }
        } else {
          resolve({ list: [] });
        }
      });
    },

    // 按设备名搜索
    searchByDeviceName(params) {
      if (params.isSearchClick) {
        this.pageNoName = 1;
      }
      let searchParams = {
        deviceName: this.searchText,
        pageSize: DEVICE_TREE_PAGE_SIZE,
        pageNo: this.pageNoName
      };
      console.log(' this.cardInfo.accessToken', this.cardInfo.accessToken);
      return requestApi({
          url: API_URLS.getCusDevices,
          method: 'post',
          data: { ...searchParams },
          headers:{
            AccessToken: this.cardInfo.accessToken
          }
        }).then((res) => {
          console.log('searchByDeviceName', res);
          if (res && res.data) {
            let list = res.data.deviceList.map((item) => {
              return {
                ...item,
                cloudStatus: item.cloudStatus || false,
                key: '' + item.deviceCode,
                isLeaf: true,
                selectable: true,
                checkable: true,
                title: item.deviceName,
                scopedSlots: {
                  title: 'title',
                  icon: 'deviceIcon',
                  switcherIcon: 'deviceSwitcherIcon'
                },
                belongTreeType: this.treeType,
                searchFirstLevel: 1 // 搜索结果的首层（不展示层级设备数量和在线数量，搜索关键字高亮）
              };
            });
            this.searchSortArr = list.length > 0 ? list[list.length - 1].sortArr?.join(',') : '';
            // 返回数量与单页请求数量一致时，则认为还有下一页
            this.showMore = list.length === DEVICE_TREE_PAGE_SIZE;
            this.pageNoName = this.pageNoName + 1;
            return { list };
          } else {
            res && res.msg && this.$message.error(res.msg);
            return { list: [] };
          }
        })
        .catch(() => {
          return { list: [] };
        });
    },
    // 按设备码搜索
    searchByDeviceCode(params) {
      if (params.isSearchClick) {
        this.pageNoCode = 1;
      }
      let searchParams = {
        deviceCode: this.searchText,
        pageSize: DEVICE_TREE_PAGE_SIZE,
        pageNo: this.pageNoCode
      };
      return requestApi({
          url: API_URLS.getCusDevices,
          method: 'post',
          data: { ...searchParams },
          headers:{
            AccessToken: this.cardInfo.accessToken
          }
        }).then((res) => {
          if (res?.code === 0) {
            let list = res.data.deviceList.map((item) => {
              return {
                ...item,
                cloudStatus: item.cloudStatus || false,
                key: '' + item.deviceCode,
                isLeaf: true,
                selectable: true,
                checkable: true,
                title: item.deviceName,
                scopedSlots: {
                  title: 'title',
                  icon: 'deviceIcon',
                  switcherIcon: 'deviceSwitcherIcon'
                },
                belongTreeType: this.treeType,
                searchFirstLevel: 1 // 搜索结果的首层（不展示层级设备数量和在线数量，搜索关键字高亮）
              };
            });
            this.searchSortArr = list.length > 0 ? list[list.length - 1].sortArr?.join(',') : '';
            // 返回数量与单页请求数量一致时，则认为还有下一页
            this.showMore = list.length === DEVICE_TREE_PAGE_SIZE;
            this.pageNoCode = this.pageNoCode + 1;
            return { list };
          } else {
            res && res.msg && this.$message.error(res.msg);
            return { list: [] };
          }
        })
        .catch(() => {
          return { list: [] };
        });
    },

    // 获取设备列表
    getRegionDeviceList(params, showLoading) {
      return this.$_api.device
        .getTreeDeviceList(params, {
          loadingKey: !showLoading ? '' : 'getSearchCusTreeLoading'
        })
        .then((res) => {
          if (res && res.code === 0) {
            const { deviceList = [], total = 0 } = res;
            let list = deviceList.map((item) => {
              return {
                ...item,
                cloudStatus: item.cloudStatus || item.videoCloudStatus || false,
                key: '' + item.deviceCode,
                isLeaf: true,
                selectable: true,
                title: item.deviceName,
                scopedSlots: {
                  title: 'title',
                  icon: 'deviceIcon',
                  switcherIcon: 'deviceSwitcherIcon'
                },
                belongTreeType: this.treeType
              };
            });
            return {
              list,
              pagination: {
                pageNo: params.pageNo,
                pageSize: DEVICE_TREE_PAGE_SIZE,
                total: total
              },
              isDevice: true // 表示返回的是设备列表
            };
          } else {
            res && res.msg && this.$message.error(res.msg);
            return {
              list: [],
              pagination: {
                pageNo: params.pageNo,
                pageSize: DEVICE_TREE_PAGE_SIZE
              },
              error: res?.code || -1,
              isDevice: true // 表示返回的是设备列表
            };
          }
        });
    },

    // 批量获取节点设备数量
    updateListDeviceNum(parentRealRegionCode, regionList, showLoading) {
      return new Promise((resolve) => {
        console.log('updateListDeviceNum-parentRealRegionCode:', parentRealRegionCode);
        if (!regionList || regionList.length === 0) return resolve([]);
        let params = {
          type: this.treeType,
          pRegionCode: parentRealRegionCode
          // regionId: regionIds
        };

        Promise.all([
          this.$_api.device.getReginWithStatisticListNew(params, {
            loadingKey: !showLoading ? '' : 'getSearchCusTreeLoading'
          }),
          this.$_api.device.getRegionOnlineDeviceCount(params, {
            loadingKey: !showLoading ? '' : 'getSearchCusTreeLoading'
          })
        ]).then(([[, res1], [, res2]]) => {
          console.log('获取目录在线数和设备总数：', res1, res2);
          if (res1?.data?.length > 0) {
            regionList = regionList.map((item) => {
              let numInfo = res1.data.find((itm) => itm.regionCode === item.realRegionCode);
              // console.log(`节点"${item.name}"有${numInfo.deviceCount}台设备`);
              numInfo && (item.deviceCount = parseInt(numInfo.deviceCount) || 0);
              return item;
            });
          }
          if (res2?.data?.length > 0) {
            regionList = regionList.map((item) => {
              let numInfo = res2.data.find((itm) => itm.regionCode === item.realRegionCode);
              // console.log(`节点"${item.name}"有${numInfo.deviceCount}台在线设备`);
              numInfo && (item.onlineDeviceCount = parseInt(numInfo.onlineCount) || 0);
              return item;
            });
          }
          resolve(regionList);
        });
      });
    },

    // 获取某个节点设备数量
    getNodeDeviceNum(regionId, showLoading) {
      let params = {
        type: this.treeType,
        regionId: regionId
      };
      return this.$_api
        .getReginWithStatisticList(params, {
          loadingKey: !showLoading ? '' : 'getSearchCusTreeLoading'
        })
        .then((res) => {
          if (res?.data?.length > 0) {
            return {
              deviceCount: res.data[0]?.deviceCount || 0
            };
          } else {
            return {
              deviceCount: 0
            };
          }
        });
    },

    // 多级树结构插入子节点数据
    insertTreeChildren(arr, parentId, nodeList, childrenPagination, updateParent) {
      let flag = false,
        pageNo = childrenPagination.pageNo || 0; // children有设备节点时pageNo不为0
      if (arr.length > 0) {
        for (let i = 0, len = arr.length; i < len; i++) {
          if (arr[i].regionCode === parentId) {
            let children = nodeList;
            // 找到与parentId对应的节点
            if (pageNo) {
              // children有设备节点
              // 分页加载更多按钮节点
              let loadMoreNode = {
                  parentKey: '' + parentId,
                  nodeType: 'loadMore', // 加载更多节点标识
                  key: `${parentId}/loadMore-${pageNo}`,
                  isLeaf: true,
                  selectable: false,
                  title: '加载更多',
                  scopedSlots: {
                    title: 'loadTitle'
                  },
                  nextPage: pageNo + 1,
                  parentNodeDataRef: arr[i]
                },
                // 默认节点分页信息，用于初始化数据
                defaultPagination = {
                  pageNo: pageNo,
                  pageSize: DEVICE_TREE_PAGE_SIZE,
                  total: 0
                },
                // 最终挂载到目录节点上的pagination
                pagination = {
                  ...(arr[i].childrenPagination || defaultPagination),
                  ...childrenPagination
                },
                // 当前是否展示“加载更多”按钮
                showLoadMoreNode = pageNo * DEVICE_TREE_PAGE_SIZE < pagination.total;
              // 过滤掉之前添加的“加载更多”节点，请求第一页时原有children内容清空
              children =
                pageNo === 1
                  ? []
                  : (arr[i].children || []).filter((item) => item.nodeType !== 'loadMore');
              // 添加当前分页设备列表数据
              children.push(...nodeList);
              // 添加“加载更多”按钮节点
              showLoadMoreNode && children.push(loadMoreNode);

              arr[i].childrenPagination = pagination;
            }
            updateParent && (arr[i] = { ...arr[i], ...updateParent }); // 更新父节点属性
            arr[i].children = children || [];
            // 插入keyPath
            arr[i].children.forEach((item) => {
              item.keyPath = `${arr[i].keyPath}/${item.key}`;
              item.pathName = `${arr[i].pathName}/${item.name || item.deviceName}`;
            });
            flag = true;
            break;
          } else if (arr[i].children && arr[i].children.length > 0) {
            flag = this.insertTreeChildren(
              arr[i].children,
              parentId,
              nodeList,
              childrenPagination,
              updateParent
            ).flag;
            if (flag) {
              break;
            }
          }
        }
      }
      return {
        flag,
        arr
      };
    },

    // 展开节点
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
    },

    // 点击树节点
    clickNode(e) {
      if (e && e.deviceCode) return;
      this.switchExpand(e.key);
    },

    // 切换展开/合并节点
    switchExpand(key) {
      let index = this.expandedKeys.indexOf(key);
      if (index > -1) {
        this.expandedKeys.splice(index, 1); // 合并
      } else {
        this.expandedKeys.push(key); // 展开
      }
    }
  }
};

export default searchTreeMixin;
